package com.bawei.broadcast

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View

class MainActivity : AppCompatActivity() {
    private val receiver = TwoBroadcastReceiver()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //onCreate：动态注册广播
        registerReceiver()
    }
    //动态注册广播
    fun registerReceiver(){
        val intentFilter = IntentFilter()
        intentFilter.addAction("com.bawei.wuxu")
        intentFilter.addAction("com.bawei.youxu")
        intentFilter.priority = 100 //优先级
        registerReceiver(receiver,intentFilter)
    }
    //onDestroy :解除注册
    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver)
    }
    /*****************发送广播******************/
    //发送无序广播：所有广播接受者同时收到
    fun send(view: View) {
        val intent = Intent("com.bawei.wuxu")
        sendBroadcast(intent)
        //发送广播后2秒注册
//        Thread{
//            Thread.sleep(2000)
//            registerReceiver()
//        }.start()
    }
    //发送有序广播：同一时刻只有一个接受者，先看优先级，再看注册方式
    fun sendOrder(view: View) {
        val intent = Intent("com.bawei.youxu")
        sendOrderedBroadcast(intent,null)
    }
    //发送粘性广播
    fun sendSticky(view: View) {
        val intent = Intent("com.bawei.wuxu")
        sendStickyBroadcast(intent)
        //发送广播后2秒注册
        Thread{
            Thread.sleep(2000)
            registerReceiver()
        }.start()

    }
    /*************广播接收器**************/
    //静态注册方案
    class OneBroadcastReceiver:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            Thread.sleep(20*1000)//ANR 超过10秒
            if("com.bawei.wuxu".equals(intent?.action)){
                Log.d("ytx", "one: 接受到无序广播")
            }else if("com.bawei.youxu".equals(intent?.action)){
                Log.d("ytx", "one: 接受到有序广播")
            }

        }

    }
    //动态注册方案
    class TwoBroadcastReceiver:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            Thread.sleep(20*1000)
            if("com.bawei.wuxu".equals(intent?.action)){
                Log.d("ytx", "two: 接受到无序广播")
            }else if("com.bawei.youxu".equals(intent?.action)){
                Log.d("ytx", "two: 接受到有序广播")
                abortBroadcast() //将广播中断拦截
            }
        }

    }




}